<?php

namespace app\task;

use app\service\AutoSettlementService;

class AutoSettlementTask
{
    /**
     * 执行自动结算任务
     */
    public function execute()
    {
        try {
            error_log('开始执行自动结算任务: ' . date('Y-m-d H:i:s'));
            
            $autoSettlementService = AutoSettlementService::getInstance();
            
            // 1. 先发送结算通知
            $notificationResult = $autoSettlementService->sendSettlementNotifications();
            error_log('结算通知发送结果: ' . json_encode($notificationResult));
            
            // 2. 然后执行自动结算
            $settlementResult = $autoSettlementService->processAutoSettlement();
            error_log('自动结算结果: ' . json_encode($settlementResult));
            
            return [
                'success' => true,
                'message' => '自动结算任务执行完成',
                'data' => [
                    'notifications' => $notificationResult,
                    'settlements' => $settlementResult
                ]
            ];
            
        } catch (\Exception $e) {
            error_log('自动结算任务失败: ' . $e->getMessage());
            
            return [
                'success' => false,
                'message' => '自动结算任务执行失败: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }
    
    /**
     * 手动触发自动结算（用于测试或管理）
     */
    public function manualTrigger()
    {
        return $this->execute();
    }
}
